import React, { useState, useEffect } from 'react';
import { View, Text, Image, Input } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useSelector } from 'react-redux';
import bear2 from '@/assets/imgs/bear2.png';
import { searchRoleListApi, bindRoleApi, addRoleMessageApi } from '@/api/handleUserAccount.js';
import './RoleSelect.scss';

const RoleSelect = () => {
  const [roleList, setRoleList] = useState([]);
  const [userRoles, setUserRoles] = useState([]);
  const [customRoleName, setCustomRoleName] = useState('');
  const [isCustomCreate, setIsCustomCreate] = useState(false);
  const userInfo = useSelector(state => state.user.userInfo);

  useEffect(() => {
    const fetchRoles = async () => {
      setUserRoles(userInfo?.roles?.map(item => item.roleCode) || []);
      const result = await searchRoleListApi();
      setRoleList(result ? result.reverse() : []);
    };
    fetchRoles();
  }, [userInfo]);

  const goHome = () => {
    Taro.redirectTo({ url: 'pages/home/home' });
  };

  const roleSelect = async (id) => {
    const bindResult = await bindRoleApi({ roleCode: id });
    if (bindResult) {
      goHome();
    }
  };

  const addCustomRole = () => {
    setIsCustomCreate(true);
  };

  const goBackCreateRole = () => {
    setIsCustomCreate(false);
  };

  const createCustomRole = async () => {
    if (customRoleName) {
      const res = await addRoleMessageApi({ roleName: customRoleName });
      if (res) {
        goHome();
      }
    } else {
      Taro.showToast({ title: '请输入信息', icon: 'none' });
    }
  };

  return (
    <View className="roleSelect">
      <View className="guide">
        <Text>请选择你的身份角色</Text>
        <Text className="explain">（我们会为你提供个性化计划定制清单）</Text>
      </View>

      {!isCustomCreate ? (
        <View className="role">
          {roleList.map(item => (
            <View
              key={item.roleCode}
              className={`role-item ${userRoles?.includes(item.roleCode) ? 'exitRole' : ''}`}
              onClick={() => !userRoles?.includes(item.roleCode) && roleSelect(item.roleCode)}
            >
              {item.roleName}
            </View>
          ))}
          <View className="role-item" onClick={addCustomRole}>
            其他(没有预设模板，可自由发挥)
          </View>
        </View>
      ) : (
        <View className="customRole">
          <Text>请输入角色名称：</Text>
          <Input value={customRoleName} onInput={(e) => setCustomRoleName(e.target.value)} type="text" />
          <View className="handleBtn">
            <View className="btn" onClick={goBackCreateRole}>返回</View>
            <View className="btn" onClick={createCustomRole}>创建</View>
          </View>
        </View>
      )}

      <View className="speak">
        <View className="box">
          <Text>Hello，你终于来啦！</Text>
          <br />
          <Text>快来随我一起开始吧！</Text>
        </View>
        <View>
          <Image className="bear" src={bear2} alt="" />
        </View>
      </View>
    </View>
  );
};

export default RoleSelect;